<?php

namespace app\admin\controller;

use app\admin\model\Order as orderModel;
use app\admin\model\State as stateModel;
use app\admin\model\Money as moneyModel;
use app\admin\model\Track as trackModel;
use app\admin\validate\OrderValidate;
use tool\Log;

class Order extends Base
{
    public function __construct() {
		parent::__construct();
        $this->order = new \app\admin\model\Order();
		$this->assign('notes', $this->order->notes);
	}
    // 订单列表
    public function index1()
    {
        if (request()->isAjax()) {

            $limit = input('param.limit');
            $name = input('param.name');

            $where = [];
            if (!empty($name)) {
                $where[] = ['name', 'like', $name . '%'];
            }

            // $order = new orderModel();
            $list = $this->order->getOrders($limit, $where);

            if (0 == $list['code']) {

                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }

        return $this->fetch();
    }

    // 联合查询 取得用户信息和收支情况
    public function index()
    {
        if (request()->isAjax()) {

            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $order = new orderModel();
            $list = $order->getOrderMoney($limit, $where);

            if (0 == $list['code']) {

                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }

        return $this->fetch();
    }

    // 今天订单
    public function today()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'today';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 昨天订单
    public function yesterday()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'yesterday';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 本周订单
    public function week()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'week';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 上周订单
    public function lastWeek()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'last week';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 本月订单
    public function month()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'month';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 上月订单
    public function lastMonth()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'last month';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 今年订单
    public function year()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'year';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 去年订单
    public function lastYear()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $whereTime = 'last year';
            $order = new orderModel();
            $list = $order->getOrderDays($limit, $whereTime);


            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 添加订单
    public function add()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $validate = new OrderValidate();
            if (!$validate->check($param)) {
                return ['code' => -1, 'data' => '', 'msg' => $validate->getError()];
            }

            $order = new orderModel();
            $res = $order->addOrder($param);

            Log::write("添加订单：" . $param['name']);

            return json($res);
        }

//        $this->assign([
//            'roles' => (new \app\admin\model\Role())->getAllRoles()['data']
//        ]);

        return $this->fetch('add');
    }

    // 编辑订单
    public function edit()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $validate = new OrderValidate();
            if (!$validate->scene('edit')->check($param)) {
                return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
            }


            $order = new orderModel();
            $res = $order->editOrder($param);

            Log::write("编辑订单：" . $param['name']);

            return json($res);
        }

        $orderId = input('param.id');
        $order = new orderModel();

        $this->assign([
            'order' => $order->getOrderById($orderId)['data'],
        ]);

        return $this->fetch('edit');
    }

    // 修改单个订单的备注信息
    public function editInfo()
    {
        if (request()->isAjax()) {
            $param['id'] = input('param.id');
            $param['info'] = input('param.info');
            $order = new orderModel();
            if (false !== $order->save($param, ['id' => $param['id']])) {
                return reMsg(0, '', '备注修改成功');
            } else {
                return reMsg(-1, '', '备注修改失败');
            }
        }
    }

    /**
     * 删除订单
     * @return \think\response\Json
     */
    public function del()
    {
        if (request()->isAjax()) {

            $orderId = input('param.id');

            $order = new orderModel();
            $res = $order->delOrder($orderId);
            //删除数据需要同时删除 money,state,track三表中的相关数据
            stateModel::where('order_id', 'in', $orderId)->delete();
            moneyModel::where('order_id', 'in', $orderId)->delete();
            trackModel::where('order_id', 'in', $orderId)->delete();

            Log::write("删除订单：" . $orderId);

            return json($res);
        }
    }

    public function detail($id = 0)
    {
        $id = input('id/d', 1);
        $detail = orderModel::find($id);
        $this->assign('detail', $detail);

        $stateList = stateModel::where('order_id', $id)->order('add_time desc')->select();
        $this->assign('stateList', $stateList);
        $moneyList = moneyModel::where('order_id', $id)->order('add_time desc')->select();
        $this->assign('moneyList', $moneyList);
        $trackList = trackModel::where('order_id', $id)->order('add_time desc')->select();
        $this->assign('trackList', $trackList);

        //总收入 总支出
        $total_profit = moneyModel::where('order_id', $id)->sum('profit');
        $total_pay = moneyModel::where('order_id', $id)->sum('pay');
        $this->assign('totalProfit', $total_profit);
        $this->assign('totalPay', $total_pay);

        $this->assign('orderId', $id);//当前订单的ID
        $this->assign('oldState', $detail['state']);//当前状态
        return $this->fetch();
    }

    public function addState()
    {
        if (request()->isPost()) {

            $param = input('post.');
            $id = $param['order_id'];

            $state = new stateModel();
            $res = $state->addState($param);

            //同时更新订单表中的状态
            $orderParams['state'] = $param['state'];
            $order = new orderModel();
            $order->save($orderParams, ['id' => $id]);

            Log::write("更新订单状态信息");

            return json($res);
        }
        $orderId = input('param.order_id/d');
        $oldState = input('param.old_state/d');
        $this->assign('orderId', $orderId);//当前订单的ID
        $this->assign('oldState', $oldState);//当前订单的ID

        return $this->fetch();
    }

    public function addMoney()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $money = new moneyModel();
            $res = $money->addMoney($param);

            Log::write("更新订单收入与支出状态信息");

            return json($res);
        }
        $orderId = input('param.order_id/d');
        $this->assign('orderId', $orderId);//当前订单的ID

        return $this->fetch();
    }

    public function addTrack()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $track = new trackModel();
            $res = $track->addTrack($param);

            Log::write("更新订单二次跟踪信息");

            return json($res);
        }
        $orderId = input('param.order_id/d');
        $this->assign('orderId', $orderId);//当前订单的ID

        return $this->fetch();
    }

    // 待处理订单列表
    public function state1()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 1;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 待就诊订单列表
    public function state2()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 2;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 待确认订单列表
    public function state3()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 3;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 已就诊有效订单列表
    public function state4()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 4;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 已就诊无效订单列表
    public function state5()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 5;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 未就诊订单列表
    public function state6()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 6;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }

    // 已取消订单列表
    public function state7()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['a.name|a.phone|a.idcard|a.hospital', 'like', '%' . $keywords . '%'];
            }
            $state = 7;

            $order = new orderModel();
            $list = $order->getOrderByState($limit, $where, $state);

            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }
}